<?php

/**
 * 图形校验码
 */
namespace App\Service\Qrcode;

use App\Service\BaseService;

class VerifyImg extends BaseService
{
    public $text            = null; //验证码上的文字
    private $fontSize       = 15;   //字体大小
    private $width          = 220;  //图片宽度
    private $height         = 40;   //图片高度
    private $fronts         = 2;   //字体
    const VERIFY_KEY        = 'VERIFY_KEY_';
    const rdb               = 2;
    /**
     * 设置图形校验码结果到服务端
     * @param string $setKey
     * @param string $_text_value
     */
    public function setQrCode( $setKey = NULL,$_text_value = NULL ) {
        $redis = $this->getRedisObj();
        $redis->select(self::rdb);
        $redis->setex(self::VERIFY_KEY.$setKey,60*10,$_text_value);
    }
    
    /**
     * 检查计算图形校验码正确性
     * @param string $authKey
     * @param string $code
     */
    public function checkQrCode( $authKey = NULL, $code = NULL ) {
        //toDo here is your code
        if(!$code) {
            return false;
        }
        $redis = $this->getRedisObj();
        $redis->select(self::rdb);
        return $code == $redis->get(self::VERIFY_KEY.$authKey);
    }
    
    /**
     * 删除缓存key
     * @param $authKey
     */
    public function delQrCodeCache($authKey = NULL) {
        $redis = $this->getRedisObj();
        $redis->select(self::rdb);
        $redis->del(self::VERIFY_KEY.$authKey);
    }
    
    /**
     * 生成图形校验码
     * @param string $setKey [自定义key前缀]
     */
    public function getQrcodeImg( $setKey = NULL ) 
    {
        
        $_config = array('+','x');
        $_calc   = $_config[array_rand($_config)];
        $_before = rand(1,10);
        $_after  = rand(1,10);
        switch ($_calc)
        {
            case '+':$_text_value = $_before + $_after;break;
            case 'x':$_text_value = $_before * $_after;break;
        }
        
        //获取计算文本结果
        $this->setQrCode($setKey,$_text_value);
        //拼接文本
        $this->text = (string)(" " .$_before ." ".$_calc." ".$_after)." ".'=?';        
        //引入图形验证码插件
        $config = new \EasySwoole\VerifyCode\Conf();
        $config->setImageHeight($this->height);
        $config->setImageWidth($this->width);
        $config->setFontSize($this->fontSize);
        $config->setFonts($this->fronts);
        $config->setUseNoise(false);
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);
        
        //重写验证码
        // $img_code = mt_rand(1000,9999);
        $result = $code->DrawCode($this->text);
        //系统验证码
        //$result = $code->DrawCode();
        //$img_code = $result->getImageCode();
        return $result->getImageByte();
    }
}
